package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bb.dd.BeiduoPlatform;
import com.igexin.sdk.PushManager;
import com.jml.zlhq.app.AppConfig;
import com.jml.zlhq.app.AppContext;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.DownAdapter;
import com.jml.zlhq.app.adapter.GridViewAdapter;
import com.jml.zlhq.app.adapter.IBaseAdapter;
import com.jml.zlhq.app.adapter.MainFaXianAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.CommonDialog;
import com.jml.zlhq.app.widgets.ControllViewPager;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yql.dr.sdk.DRActivity;
import com.yql.dr.sdk.DRSdk;
import com.zkmm.appoffer.ZkmmAppOffer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cn.dow.android.DOW;
import cn.waps.AppConnect;
import net.youmi.android.listener.Interface_ActivityListener;
import net.youmi.android.offers.OffersBrowserConfig;
import net.youmi.android.offers.OffersManager;

public class LingGanFragment extends BaseFragment implements
		OnItemClickListener {
	private RelativeLayout adsLay;
	private ControllViewPager adsViewPager;
	private PagerAdapter adsAdapter;
	private LinearLayout tipsLay;
	private ScrollView scrollView;
	public static boolean freshPage;

	@SuppressWarnings("unused")
	private LinearLayout loadInfo;
	private TextView loadInfoText, jinbi, jine, qiandao, tixian, rightText;
	private JSONObject data, meinfo;
	private JSONArray tuijian;
	private JSONArray tuijianGV;

	private ListView listview;
	private IBaseAdapter readapter;
	private List<JSONObject> listItems = new ArrayList<JSONObject>();

	private GridView gridView;
	private IBaseAdapter downAdapter;
	private List<Object[]> dwonItems = new LinkedList<Object[]>();
	private List<JSONObject> dwonItems2 = new LinkedList<JSONObject>();

	private List<ImageView> tips = new LinkedList<ImageView>();
	private List<ImageView> images = new LinkedList<ImageView>();
	private List<JSONObject> items = new LinkedList<JSONObject>();
	private String bToken = "";

	private LinkedList<LinearLayout> downLays = new LinkedList<LinearLayout>();

	final static int PHOTO_CHANGE_TIME = 3000;// 图片自动切换时间
	private long tag = System.currentTimeMillis();
	private static final String TAG = "LingGanFragment";
	private View content_header_center_lay;

	private ZkmmAppOffer appOffer;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		private long tag = 0;

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				jinbi.setText(BaseTools.getFrom("account_fees", meinfo, "0"));
				jine.setText("金币");
				scrollView.smoothScrollTo(0, 0);
				break;
			case 2:
				final CommonDialog show = new CommonDialog(activity, true);
				show.show(true, true, false, "签到",
						msg.getData().getString("text"), "确定", "",
						new OnClickListener() {
							@Override
							public void onClick(View v) {
								show.dismiss();
							}
						}, null);
				break;
			case 3:
				if (items.isEmpty())
					return;
				initDown2();
				for (int i = 0; i < items.size(); i++) {
					final JSONObject tjb = items.get(i);
					ImageView tip = new ImageView(activity);
					LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams(
							UIUtil.dip2px(activity, 10), UIUtil.dip2px(
									activity, 10));
					mlp.setMargins(UIUtil.dip2px(activity, 10), 0, 0, 0);
					tip.setImageResource(i == 0 ? R.drawable.bg_circle_sel_10
							: R.drawable.bg_circle_white_10);
					tip.setLayoutParams(mlp);
					tips.add(tip);
					tipsLay.addView(tip);
					ImageView imageView = new ImageView(activity);
					int height = UIUtil.dip2px(activity, 265);
					imageView.setLayoutParams(new LinearLayout.LayoutParams(
							LayoutParams.MATCH_PARENT, height));
					imageView.setScaleType(ScaleType.FIT_XY);
					ImageLoader
							.getInstance()
							.displayImage(
									URLs.IMAGE_HOST
											+ BaseTools.getFrom("image", tjb)
											+ "_scal_720x720.jpg",
									imageView,
									UIUtil.getImageLoaderDisplayOptions(R.drawable.icon_default_f));

					imageView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if (BaseTools.getFrom("href_type", tjb).equals("0")) {
								/*
								 * toweb(BaseTools.getFrom("link",tjb), bToken,
								 * activity)
								 */;
								Bundle data = new Bundle();
								data.putString("title", "活动详情");
								data.putString("id",
										BaseTools.getFrom("link", tjb));
								UIUtil.openActivity(activity,
										HuodongDetailActivity.class, data);
							} else {
								Intent intent = new Intent();
								intent.setAction("android.intent.action.VIEW");
								Uri content_url = Uri.parse(BaseTools.getFrom(
										"link", tjb) + "?BTOKEN=" + bToken);
								intent.setData(content_url);
								activity.startActivity(intent);
								/*
								 * Bundle data = new Bundle();
								 * data.putString("url",
								 * BaseTools.getFrom("link"
								 * ,tjb)+"?btoken="+bToken);
								 * UIUtil.openActivity(activity,
								 * CommonWebActivity.class, data);
								 */
							}
						}
					});
					images.add(imageView);
				}
				adsAdapter.notifyDataSetChanged();
				adsViewPager.setCurrentItem(0);
				for (int i = 0; i < tuijian.length(); i++) {
					try {
						listItems.add(tuijian.getJSONObject(i));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				readapter.notifyDataSetChanged();
				scrollView.smoothScrollTo(0, 0);
				LingGanFragment.this.tag = System.currentTimeMillis();
				this.sendEmptyMessageDelayed(4, PHOTO_CHANGE_TIME);
				break;
			case 4:
				if (items.isEmpty())
					return;
				if (this.tag == 0 || this.tag == LingGanFragment.this.tag) {
					this.tag = LingGanFragment.this.tag;
					int index = adsViewPager.getCurrentItem();
					adsViewPager.setCurrentItem((index + 1) % items.size());
					this.sendEmptyMessageDelayed(4, PHOTO_CHANGE_TIME);
				} else {
					this.tag = LingGanFragment.this.tag;
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		
		// LinearLayout leftLay = (LinearLayout)
		// pageView.findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) pageView
				.findViewById(R.id.content_header_right_lay);
		// leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) pageView
				.findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.VISIBLE);
		content_header_center_lay = pageView
				.findViewById(R.id.content_header_center_lay);
		content_header_center_lay.setOnClickListener(this);
		ImageView roghtImage1 = (ImageView) pageView
				.findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		rightText = (TextView) pageView
				.findViewById(R.id.content_header_right_text);
		rightText.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.fillet_fff9f8));
		rightText.setText("登录");
		TextView leftText = (TextView) pageView
				.findViewById(R.id.content_header_left_text);
		leftText.setText("赚零花钱");
		leftText.setVisibility(View.VISIBLE);
		TextView centerText = (TextView) pageView
				.findViewById(R.id.content_header_center_text);
		centerText.setVisibility(View.INVISIBLE);
		TextView centerChosed = (TextView) pageView
				.findViewById(R.id.content_header_center_text2);
		centerChosed.setVisibility(View.GONE);

		// LinearLayout newTask = (LinearLayout)
		// pageView.findViewById(R.id.main_lingan_newtask_lay);
		LinearLayout downloadTask = (LinearLayout) pageView
				.findViewById(R.id.main_lingan_downloadtask_lay);
		downloadTask.setTag("youmi");
		downLays.add(downloadTask);
		LinearLayout downloadbaiduTask = (LinearLayout) pageView
				.findViewById(R.id.main_lingan_downloadtask_baidu_lay);
		downloadbaiduTask.setTag("baidu");
		downLays.add(downloadbaiduTask);
		// LinearLayout shareTask = (LinearLayout)
		// pageView.findViewById(R.id.main_lingan_sharetask_lay);
		LinearLayout beiduoDown = (LinearLayout) pageView
				.findViewById(R.id.main_lingan_downtk_beiduo_lay);
		beiduoDown.setTag("beiduo");
		downLays.add(beiduoDown);
		LinearLayout duomenDown = (LinearLayout) pageView
				.findViewById(R.id.main_lingan_downtk_duomeng_lay);
		duomenDown.setTag("duomeng");
		downLays.add(duomenDown);
		/*
		 * LinearLayout limeiDown = (LinearLayout)
		 * pageView.findViewById(R.id.main_lingan_downtk_meili_lay);
		 * LinearLayout wanpuDown = (LinearLayout)
		 * pageView.findViewById(R.id.main_lingan_downtk_wanpu_lay);
		 * LinearLayout dianruDown = (LinearLayout)
		 * pageView.findViewById(R.id.main_lingan_downtk_dianru_lay);
		 */

		downloadbaiduTask.setOnClickListener(this);
		// newTask.setOnClickListener(this);
		downloadTask.setOnClickListener(this);
		// shareTask.setOnClickListener(this);
		beiduoDown.setOnClickListener(this);
		duomenDown.setOnClickListener(this);
		/*
		 * limeiDown.setOnClickListener(this);
		 * wanpuDown.setOnClickListener(this);
		 * dianruDown.setOnClickListener(this);
		 */

		adsLay = (RelativeLayout) pageView.findViewById(R.id.lingan_ads);
		int ph = UIUtil.winWidth * 34 / 64;
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, ph);
		adsLay.setLayoutParams(lp);
		adsViewPager = (ControllViewPager) pageView
				.findViewById(R.id.lingan_ads_pager);
		adsAdapter = new ImgAdAdapter(images);
		adsViewPager.setAdapter(adsAdapter);
		tipsLay = (LinearLayout) pageView.findViewById(R.id.lingan_ads_tiplay);
		adsViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg) {
				for (ImageView tip : tips) {
					tip.setImageResource(R.drawable.bg_circle_white_10);
				}
				tips.get(arg).setImageResource(R.drawable.bg_circle_sel_10);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		TextView hddt = (TextView) pageView
				.findViewById(R.id.lingan_nav_sheying);
		TextView wxhb = (TextView) pageView
				.findViewById(R.id.lingan_nav_shexiang);
		TextView zfbhb = (TextView) pageView
				.findViewById(R.id.lingan_nav_huazhuang);
		TextView mfhf = (TextView) pageView
				.findViewById(R.id.lingan_nav_zhuchi);
		hddt.setOnClickListener(this);
		wxhb.setOnClickListener(this);
		zfbhb.setOnClickListener(this);
		mfhf.setOnClickListener(this);

		jinbi = (TextView) pageView.findViewById(R.id.main_lingan_jinbi);
		jine = (TextView) pageView.findViewById(R.id.main_lingan_jine);
		qiandao = (TextView) pageView.findViewById(R.id.main_lingan_qiandao);
		tixian = (TextView) pageView.findViewById(R.id.main_lingan_tixian);
		qiandao.setOnClickListener(this);
		tixian.setOnClickListener(this);

		loadInfo = (LinearLayout) pageView.findViewById(R.id.load_info_lay);
		loadInfoText = (TextView) pageView.findViewById(R.id.load_info);
		loadInfoText.setOnClickListener(this);
		// url = URLs.MAIN_LINGGAN_SEARCH;
		scrollView = (ScrollView) pageView
				.findViewById(R.id.main_lingan_scroll);
		listview = (ListView) pageView
				.findViewById(R.id.main_lingan_recommend_list);
		readapter = new MainFaXianAdapter(activity, listItems, false);
		listview.setAdapter(readapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/*
				 * int index = new Long(id).intValue();
				 * toweb(BaseTools.getFrom("_id", listItems.get(index)), bToken,
				 * activity);
				 */
				int index = new Long(id).intValue();
				Bundle data = new Bundle();
				data.putString("title", "活动详情");
				data.putString("id",
						BaseTools.getFrom("_id", listItems.get(index)));
				UIUtil.openActivity(activity, HuodongDetailActivity.class, data);
			}
		});

		gridView = (GridView) pageView.findViewById(R.id.main_lingan_gridview);
		downAdapter = new GridViewAdapter(activity, dwonItems2);
		gridView.setAdapter(downAdapter);
		// gridView.setOnItemClickListener(this);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				try {
					if (dwonItems2.get(position).getInt("href_type") == 0) {
						Bundle data = new Bundle();
						data.putString("title", "活动详情");
						data.putString("id", dwonItems2.get(position)
								.getString("link"));
						UIUtil.openActivity(activity,
								HuodongDetailActivity.class, data);
					} else {
						Bundle data = new Bundle();
						data.putString("url", dwonItems2.get(position)
								.getString("link"));
						UIUtil.openActivity(activity, WebHuoDongActivity.class,
								data);

					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		// initDown2();

		freshPage = false;
		if (urlParam == null)
			urlParam = new HashMap<String, String>();
		loadData(urlParam);

		return pageView;
	}

	public static void toweb(String id, String bToken, Activity activity) {
		Bundle data = new Bundle();
		data.putString("url", URLs.APP_WEB + id + "?btoken=" + bToken);
		UIUtil.openActivity(activity, CommonWebActivity.class, data);
	}

	public void initDown2() {
		dwonItems2.clear();
		for (int i = 0; i < tuijianGV.length(); i++) {
			try {
				dwonItems2.add(tuijianGV.getJSONObject(i));
				System.out.println("tuijianGV.getJSONObject(i):"
						+ tuijianGV.getJSONObject(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		downAdapter.notifyDataSetChanged();

	}

	public void initDown() {
		String adsp = AppConfig.getAppConfig(activity).get("adsp");
		dwonItems.clear();
		try {
			JSONArray adspArr = new JSONArray(""); // 正式
			// JSONArray adspArr = new JSONArray(); // 测试
			// adspArr.put(0, "youmi");
			// adspArr.put(1, "baidu");
			// adspArr.put(2, "wanpu");
			// adspArr.put(3, "beiduo");

			for (int i = 0; i < TanDianFragment.downtask.size(); i++) {
				String tag = TanDianFragment.downtask.get(i)[0].toString();
				for (int j = 0; adspArr != null && j < adspArr.length(); j++) {
					if (tag.equals(adspArr.getString(j))) {
						Object[] ttt = new Object[] {
								TanDianFragment.downtask.get(i)[0],
								TanDianFragment.downtask.get(i)[1],
								TanDianFragment.downtask.get(i)[2],
								TanDianFragment.downtask.get(i)[3] };
						switch (j + 1) {
						case 1:
							ttt[2] = R.drawable.ico_ind_1;
							break;
						case 2:
							ttt[2] = R.drawable.ico_ind_2;
							break;
						case 3:
							ttt[2] = R.drawable.ico_ind_3;
							break;
						case 4:
							ttt[2] = R.drawable.ico_ind_4;
							break;
						}
						dwonItems.add(ttt);
						break;
					}
				}
			}
			downAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			final int position, final long id) {
		String downwarming = appContext.getProperty("downwarming");
		if (StringUtil.isEmpty(downwarming) || !downwarming.equals("ok")) {
			CommonDialog dialog = new CommonDialog(activity, true);
			dialog.show(
					true,
					true,
					true,
					"友情提示",
					"赚零花钱建议您安装一款安全软件，比如腾讯管家等，以防止流量偷跑，防止手机中毒，防止后台发短信，避免恶意扣话费。<br><font color='red'>如果体验应用时遇到要发短信激活，请拒绝！</font>",
					"知道了", "不再提醒", new android.view.View.OnClickListener() {
						@Override
						public void onClick(View view) {
							((CommonDialog) view.getTag()).dismiss();
							LingGanFragment.downitemEvt(dwonItems, appContext,
									activity, LingGanFragment.this, position,
									id);
						}
					}, new android.view.View.OnClickListener() {
						@Override
						public void onClick(View view) {
							((CommonDialog) view.getTag()).dismiss();
							appContext.setProperty("downwarming", "ok");
							LingGanFragment.downitemEvt(dwonItems, appContext,
									activity, LingGanFragment.this, position,
									id);
						}
					});
		} else {
			LingGanFragment.downitemEvt(dwonItems, appContext, activity,
					LingGanFragment.this, position, id);
		}

	}

	public static void downitemEvt(List<Object[]> items, AppContext appContext,
			Activity activity, Fragment fgt, int position, long id) {
		int index = new Long(id).intValue();
		if (items.get(index)[0].toString().equals("youmi")) {
			if (appContext.isLogin()) {
				OffersBrowserConfig.setBrowserTitleText("赚零花钱");
				OffersBrowserConfig.setBrowserTitleBackgroundColor(activity
						.getResources().getColor(R.color.color_e95847));
				OffersBrowserConfig.setPointsLayoutVisibility(false);
				OffersManager.getInstance(activity).showOffersWall(
						new Interface_ActivityListener() {
							@Override
							public void onActivityDestroy(Context arg0) {
							}
						});
			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		} else if (items.get(index)[0].toString().equals("baidu")) {
			if (appContext.isLogin()) {
				UIUtil.openActivity(fgt, ShowInActivity.class, null);
			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		} else if (items.get(index)[0].toString().equals("dianru")) {
			if (appContext.isLogin()) {

				DRSdk.showOfferWall(activity, DRSdk.DR_OFFER);

			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		} else if (items.get(index)[0].toString().equals("beiduo")) {
			if (appContext.isLogin()) {
				// DRSdk.showOfferWall(activity, DRSdk.DR_OFFER);
				// Intent intent = new Intent(activity, DRActivity.class);
				// intent.putExtra(DRSdk.DR_TYPE, DRSdk.DR_OFFER);
				// activity.startActivity(intent);
				BeiduoPlatform.showOfferWall(activity);
			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		} else if (items.get(index)[0].toString().equals("duomeng")) {
			if (appContext.isLogin()) {
				DOW.getInstance(activity).show(activity);
			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		} else if (items.get(index)[0].toString().equals("wanpu")) {
			if (appContext.isLogin()) {
				AppConnect.getInstance(activity).showOffers(activity,
						appContext.getLoginUid());
			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		} else if (items.get(index)[0].toString().equals("anwo")) {
			if (appContext.isLogin()) {
				MainActivity mActivity = (MainActivity) activity;
				mActivity.AnWoAppOffer.showOffer(activity);
				// ZkmmAppOffer.showOffer(activity);
			} else {
				UIUtil.openActivity(fgt, LoginActivity.class, null, 105);
			}
		}
	}

	@Override
	public void onResume() {
		// if (appContext.isLogin() && rightText.getVisibility() ==
		// View.VISIBLE)
		// rightText.setVisibility(View.INVISIBLE);
		// if (!appContext.isLogin()
		// && rightText.getVisibility() == View.INVISIBLE)
		// rightText.setVisibility(View.VISIBLE);
		if (!appContext.isLogin()) {
			rightText.setText("登录");
		} else {
			rightText.setText("个人中心");
		}

		pageFresh = freshPage;
		super.onResume();
		freshPage = false;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		/*
		 * if(BuildConfig.DEBUG)Log.i("==fr==", freshPage+""); if(freshPage){
		 * freshPage=false; data = null; if(appContext.isLogin()){ Map<String,
		 * String> param = new HashMap<String, String>();
		 * 
		 * HttpService.getByText(URLs.MAIN_ZQDT, param, new
		 * TextHttpResponseHandler() {
		 * 
		 * @Override public void onSuccess(int arg0, Header[] arg1, String
		 * resultStr) { try { if(BuildConfig.DEBUG)Log.i("==result post==",
		 * resultStr); JSONObject result = new JSONObject(resultStr);
		 * if(result.getInt("status")==0){ data = result.getJSONObject("data");
		 * } mHandler.sendEmptyMessage(1); } catch (JSONException e) {
		 * e.printStackTrace(); } }
		 * 
		 * @Override public void onFailure(int arg0, Header[] arg1, String arg2,
		 * Throwable arg3) { UIUtil.ToastMessage(activity, "抱歉，访问失败"); } });
		 * }else{ mHandler.sendEmptyMessage(1); } }
		 */
		initme();
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 101) {
			if (appContext.isLogin()) {
				onClick(qiandao);
			} else {
				UIUtil.ToastMessage(activity, "未登录!");
			}
		}
		if (requestCode == 105) {
			if (!appContext.isLogin()) {
				UIUtil.ToastMessage(activity, "未登录!");
			} else {
				com.baidu.mobads.appoffers.OffersManager.setUserName(activity,
						appContext.getLoginUid());
				DOW.getInstance(activity).setUserId(appContext.getLoginUid());
				BeiduoPlatform.setUserId(appContext.getLoginUid());
				OffersManager.getInstance(activity).setCustomUserId(
						appContext.getLoginUid());
			}
		}
		if (requestCode == 102) {
			if (appContext.isLogin()) {
				((MainActivity) activity).chooseMenu(2);
			} else {
				UIUtil.ToastMessage(activity, "未登录!");
			}
		}

	}

	@Override
	public void loadData(Map<String, String> param) {
		if (param == null)
			param = new HashMap<String, String>();
		items.clear();
		tipsLay.removeAllViewsInLayout();
		tips.clear();
		images.clear();
		adsAdapter.notifyDataSetChanged();
		// if(appContext.isLogin()){
		String cid = PushManager.getInstance().getClientid(activity);
		param.put("auth_token", appContext.getLoginUid());
		param.put("getui_client_id", cid);
		HttpService.getByText(URLs.MAIN_ZQDT, param,
				new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, Header[] arg1,
							String resultStr) {
						try {
							if (BuildConfig.DEBUG)
								Log.i("==result post==", resultStr);
							JSONObject result = new JSONObject(resultStr);
							if (result.getInt("status") == 0) {
								data = result.getJSONObject("data");
								bToken = data.getString("BTOKEN");
								appContext.setProperty("bToken", bToken);
								JSONArray arr = data.getJSONArray("ads");
								tuijian = data.getJSONArray("list");
								tuijianGV = data.getJSONArray("ads2");
								for (int i = 0; arr != null && i < arr.length(); i++) {
									items.add(arr.getJSONObject(i));
								}
							}
							mHandler.sendEmptyMessage(3);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2,
							Throwable arg3) {
						UIUtil.ToastMessage(activity, "抱歉，访问失败");
					}
				});
		initme();
		// }else{
		// mHandler.sendEmptyMessage(3);
		// }

		/*
		 * HttpService.getByText(URLs.MAIN_ADS_LIST, param, new
		 * TextHttpResponseHandler() {
		 * 
		 * @Override public void onSuccess(int arg0, Header[] arg1, String
		 * resultStr) { try { if(BuildConfig.DEBUG)Log.i("==result post==",
		 * resultStr); JSONObject result = new JSONObject(resultStr);
		 * if(result.getInt("status")==0){ JSONArray arr =
		 * result.get("data").toString().equals("null")?new
		 * JSONArray():result.getJSONArray("data"); for (int i = 0; arr!=null &&
		 * i < arr.length(); i++) { items.add(arr.getJSONObject(i)); } } } catch
		 * (JSONException e) { e.printStackTrace(); }
		 * mHandler.sendEmptyMessage(3); }
		 * 
		 * @Override public void onFailure(int arg0, Header[] arg1, String arg2,
		 * Throwable arg3) {
		 * 
		 * } });
		 */
	}

	public void initme() {
		meinfo = null;
		if (appContext.isLogin()) {
			meinfo = appContext.getLoginUser();
		}
		mHandler.sendEmptyMessage(1);
	}

	@Override
	public void clearData() {
		pageEnd = false;
		if (urlParam == null)
			urlParam = new HashMap<String, String>();
	}

	@Override
	public void onClick(View v) {
		Bundle huodong = new Bundle();
		switch (v.getId()) {
		// case R.id.main_lingan_newtask_lay:
		// String jsonArr = "";
		// try {
		// jsonArr = tuijian.toString();
		// } catch (Exception e1) {}
		// huodong.putString("jsonArr",jsonArr);
		// UIUtil.openActivity(activity, TuiJianActivity.class, huodong);
		// break;
		case R.id.lingan_nav_shexiang:
			huodong.putString("titleStr", "拿红包");
			huodong.putInt("url", 1);
			huodong.putBoolean("isBottom", true);
			UIUtil.openActivity(activity, HuoDongActivity.class, huodong);
			break;
		case R.id.lingan_nav_huazhuang:
			huodong.putString("titleStr", "高额返现");
			huodong.putInt("url", 2);
			huodong.putBoolean("isBottom", true);
			UIUtil.openActivity(activity, HuoDongActivity.class, huodong);
			break;
		case R.id.lingan_nav_zhuchi:
			huodong.putString("titleStr", "话费流量");
			huodong.putInt("url", 3);
			huodong.putBoolean("isBottom", true);
			UIUtil.openActivity(activity, HuoDongActivity.class, huodong);
			break;
		case R.id.lingan_nav_sheying:
			huodong.putString("titleStr", "套白狼");
			huodong.putInt("url", 4);
			huodong.putBoolean("isBottom", true);
			UIUtil.openActivity(activity, HuoDongActivity.class, huodong);
			break;
		case R.id.content_header_right_lay:
			if (!appContext.isLogin()) {
				UIUtil.openActivity(this, LoginActivity.class, null, 1);
			} else {
				// 如果已经登录，就到个人中心
				UIUtil.openActivity(this, WodeActiivty.class, null);
			}

			break;
		case R.id.load_info:
			if (urlParam == null)
				urlParam = new HashMap<String, String>();
			urlParam.clear();
			loadData(urlParam);
			break;
		case R.id.main_lingan_downloadtask_lay:
			if (appContext.isLogin()) {
				OffersBrowserConfig.setBrowserTitleText("赚零花钱");
				OffersBrowserConfig.setBrowserTitleBackgroundColor(activity
						.getResources().getColor(R.color.color_e95847));
				OffersBrowserConfig.setPointsLayoutVisibility(false);
				OffersManager.getInstance(activity).showOffersWall(
						new Interface_ActivityListener() {
							@Override
							public void onActivityDestroy(Context arg0) {
								// TODO Auto-generated method stub

							}

						});
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 105);
			}
			break;
		case R.id.main_lingan_downloadtask_baidu_lay:
			if (appContext.isLogin()) {
				UIUtil.openActivity(this, ShowInActivity.class, null);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 105);
			}
			break;
		case R.id.main_lingan_downtk_beiduo_lay:
			if (appContext.isLogin()) {
				BeiduoPlatform.showOfferWall(activity);
				// UIUtil.openActivity(this, ShowInActivity.class, null);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 105);
			}
			break;
		case R.id.main_lingan_downtk_duomeng_lay:
			if (appContext.isLogin()) {
				DOW.getInstance(activity).show(activity);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 105);
			}
			break;
		/*
		 * case R.id.main_lingan_sharetask_lay: boolean isRegisterSuccess =
		 * OffersManager
		 * .getInstance(activity).registerToWx("wx0b7183085cb42444");
		 * Log.i("youmi", String.format("注册微信appid %s", isRegisterSuccess ? "成功"
		 * : "失败")); OffersBrowserConfig.setBrowserTitleText("赚零花钱");
		 * OffersBrowserConfig
		 * .setBrowserTitleBackgroundColor(activity.getResources
		 * ().getColor(R.color.color_e95847));
		 * OffersBrowserConfig.setPointsLayoutVisibility(false);
		 * OffersManager.getInstance(activity).showShareWall(new
		 * Interface_ActivityListener() {
		 * 
		 * @Override public void onActivityDestroy(Context arg0) { // TODO
		 * Auto-generated method stub
		 * 
		 * }
		 * 
		 * }); break;
		 */
		case R.id.main_lingan_qiandao:
			/*
			 * if(appContext.isLogin()){ Map<String, String>param = new
			 * HashMap<String, String>();
			 * if(appContext.isLogin())param.put("auth_token",
			 * appContext.getLoginUid());
			 * HttpService.postByText(URLs.MAIN_QIANDAO, param, new
			 * TextHttpResponseHandler() {
			 * 
			 * @Override public void onSuccess(int arg0, Header[] arg1, String
			 * resultStr) { try { if(BuildConfig.DEBUG)Log.i("==result post==",
			 * resultStr); JSONObject result = new JSONObject(resultStr); Bundle
			 * data = new Bundle(); data.putBoolean("refreash", false);
			 * if(result.getInt("status")==0){ data.putString("text",
			 * "今日签到：获得"+BaseTools.getFrom("data.fees", result, "0")+"金币!");
			 * data.putBoolean("refreash", true);
			 * LoginActivity.afterLogined(activity,new CheckBind() {
			 * 
			 * @Override public void checkBind(String phone) { //TODO } }); }
			 * else{ data.putString("text", BaseTools.getFrom("message",
			 * result)); } Message msg = new Message(); msg.what=2;
			 * msg.setData(data); mHandler.sendMessage(msg); } catch
			 * (JSONException e) { e.printStackTrace(); } }
			 * 
			 * @Override public void onFailure(int arg0, Header[] arg1, String
			 * arg2, Throwable arg3) { UIUtil.ToastMessage(activity, "抱歉，访问失败");
			 * } });
			 * 
			 * }else{ UIUtil.openActivity(this, LoginActivity.class, null,101);
			 * }
			 */
			if (appContext.isLogin()) {
				UIUtil.openActivity(this, qiandao2Activity.class, null);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 101);
			}
			break;
		case R.id.main_lingan_tixian:
			if (appContext.isLogin()) {
				((MainActivity) activity).chooseMenu(2);
			} else {
				UIUtil.openActivity(this, LoginActivity.class, null, 102);
			}
			break;
		case R.id.content_header_center_lay:
			// 搜索
			UIUtil.openActivity(activity, SearchActivity.class, null);
			break;
		default:
			break;
		}
	}

	@Override
	protected int getPageView() {
		return R.layout.main_lingan;
	}

	private class ImgAdAdapter extends PagerAdapter {
		private List<ImageView> items;

		public ImgAdAdapter(List<ImageView> items) {
			this.items = items;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public int getCount() {
			return items == null ? 0 : items.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			try {
				((ViewPager) container).removeView(items.get(position));
			} catch (Exception e) {
				// e.printStackTrace();
			}
		}

		/**
		 * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
		 */
		@Override
		public Object instantiateItem(View container, final int position) {
			try {
				((ViewPager) container).addView(items.get(position));
			} catch (Exception e) {
				e.printStackTrace();
			}

			return items.get(position);
		}
	}
}
